﻿using com.tanlingyun.baojia.Entity;
using com.tanlingyun.ViewModel;
using FluentData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.tanlingyun.DbServices
{
    public class PartService:BaseService
    {
        /// <summary>
        /// 为零件添加工序
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="ptGx"></param>
        /// <returns></returns>
        public OperateResult AddPartGx(int user_id,PartGx ptGx)
        {
            ProductService _productService = new ProductService();
            ProductPart pp = _productService.GetProductPart(ptGx.pp_id);
            if (pp == null || pp.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("零件编号{0}不存在", ptGx.pp_id) };

            GongxuService _gongXuService = new GongxuService();
            Gongxu entityGongxu = _gongXuService.GetGx(ptGx.gx_id);
            if (entityGongxu == null || entityGongxu.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("工序编号{0}不存在！", ptGx.gx_id) };

            if(entityGongxu.isCalWeight)
            {

            }
            if(entityGongxu.isDealHot)
            {

            }
            if(entityGongxu.isDealSurface)
            {

            }

            if(ptGx.ID>0)
            {
                PartGx entityPartGx = GetPartGx(ptGx.ID);
                if (entityPartGx == null || entityPartGx.status != 1)
                    return new OperateResult() { code = ResultCode.Failed,message = "更新的工序不存在" };
                if (db.Update<PartGx>("", ptGx).AutoMap(x => x.ID, x => x.status).Where(x => x.ID).Execute() > 0)
                    return new OperateResult() { code = ResultCode.Success };

            }else
            {
                ptGx.status = 1;
                if (db.Insert<PartGx>("PartGx", ptGx).AutoMap(x => x.ID).Execute() > 0)
                    return new OperateResult() { code  = ResultCode.Success };
            }

            _productService.UpdateProductPrice(user_id, ptGx.product_id);
            //ptGx.totalFee = (ptGx.prepare_time + ptGx.single_time * pp.qty)

            return new OperateResult() { code = ResultCode.Failed,message = "操作失败！" };
        }

        /// <summary>
        /// 添加原材料工序
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="Gx"></param>
        /// <returns></returns>
        public OperateResult AddMaterialGx(int user_id, MaterialGx Gx)
        {
            ProductService _productService = new ProductService();
            //验证产品
            Products entityProduct = _productService.GetProduct(Gx.product_id);
            if (entityProduct == null || entityProduct.Status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品编号{0}不存在！", Gx.product_id) };
            //验证零件
            Parts entityPart = _productService.GetPart(Gx.part_id);
            if (entityPart == null || entityPart.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = string.Format("产品{0}的零件{1}不存在！", entityProduct.Name, Gx.product_id) };
            //验证产品零件
            ProductPart pp = _productService.GetProductPart(Gx.pp_id);
            if (pp == null || pp.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "零件信息错误！" };
            //验证材料
            RawService _rawServicce = new RawService();

            PartMaterials pm = _productService.GetPartMaterial(Gx.pm_id);
            if (pm == null || pm.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "材料信息有误！" };
            //RawMaterials entityRaw = _rawServicce.GetRaw(Gx.raw)

            GongxuService _gongxuService = new GongxuService();
            Gongxu entityGx = _gongxuService.GetGx(Gx.gx_id);
            if (entityGx == null || entityGx.status != 1)
                return new OperateResult() { code = ResultCode.Failed,message = "工序信息错误！" };

            //按重量算加工费
            if (entityGx.isCalWeight)
            {
                //热处理(不需要填写工时)
                if(entityGx.isDealHot)
                {
                    //热处理费 = (材料总重×此道工序的热重％)×此工序加工单价
                    Gx.totalFee += Math.Round((decimal)(Gx.hot_percent * pp.weight) * entityGx.price, 2);
                }
                //表面处理(不需要填写工时)
                if(entityGx.isDealSurface)
                {
                    //表面处理费=(材料总的表面积×此道工序的热重％)×此工序加工单价
                    Gx.totalFee += Math.Round((decimal)(pm.SurfaceArea * Gx.hot_percent) * entityGx.price, 2);
                }
            }else
            {
                //总工时＝准备工时+(单件工时×制造数量)
                double totalTime = Gx.prepare_time + (pm.qty * Gx.single_time);
                Gx.totalFee += Math.Round((decimal)totalTime * entityGx.price, 2);
            }

            if (db.Insert<MaterialGx>("MaterialGx", Gx).AutoMap(x => x.ID).Execute() > 0)
            {
                _productService.UpdateProductPrice(user_id,Gx.product_id);

                return new OperateResult() { code = ResultCode.Success };
            }
           
            return new OperateResult() { code = ResultCode.Failed,message = "材料工序添加失败！" };
        }

        public  OperateResult DeletePart(int user_id,int pp_id)
        {
            using (IDbContext newdb = db.UseTransaction(true))
            {
                try
                {

                    newdb.Commit();
                }
                catch
                {
                    newdb.Rollback();
                }
            }

            return new OperateResult() { code = ResultCode.Failed, message = "零件删除失败！" };
        }

        /// <summary>
        /// 获取零件工序
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="product_id"></param>
        /// <param name="pp_id"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public PageInfo<V_list_PartGx> GetPartGx(int user_id,int product_id,int pp_id,int PageIndex = 1,int PageSize = 5)
        {
            PageInfo<V_list_PartGx> vpgpage = new PageInfo<V_list_PartGx>() {
                Fields = "partgx.ID as pg_id,gongxu.name as gx_name,shuyu.Gyshuyu as gy_shuyu,partgx.product_id,partgx.part_id,partgx.pp_id,partgx.prepare_time,partgx.single_time,partgx.hot_percent,employee.name as employee",
                TableName = "partgx left join gongxu on partgx.gx_id = gongxu.ID left join shuyu on shuyu.ID = partgx.gy_id left join employee on employee.id = partgx.employee_id",
                PageIndex = PageIndex,
                PageSize = PageSize,
                OrderBy = "partgx.ID desc"
            };
            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1)
                return vpgpage;
            ProductService _productService = new ProductService();
            Products entityProduct = _productService.GetProduct(product_id);
            if (entityProduct == null || entityProduct.Status != 1)
                return vpgpage;

            if (entityUser.level_type == (int)ELevelType.Operator && entityProduct.manager_id != entityUser.parentid)
                return vpgpage;
            if (entityUser.level_type == (int)ELevelType.Manager && entityProduct.manager_id != entityUser.id)
                return vpgpage;

            string where = "product_id=" + product_id + " and pp_id=" + pp_id;
            vpgpage.Where = where;
            return GetPageInfo<V_list_PartGx>(vpgpage);
        }

        /// <summary>
        /// 获取零件工序
        /// </summary>
        /// <param name="pg_id"></param>
        /// <returns></returns>
        public PartGx GetPartGx(int pg_id)
        {
            return db.Sql("select * from PartGx where ID=@0 and status=1", pg_id).QuerySingle<PartGx>();
        }
    }
}
